package com.day46.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author 咕唧
 * @Date 2022/5/14 17:31
 * @Version 1.0
 */
public class MybatisUtils {
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static SqlSession openSession() {
        SqlSession sqlSession = tl.get();
        if (sqlSession == null) {
            sqlSession = factory.openSession();
            tl.set(sqlSession);
        }
        return sqlSession;
    }

    public static <T extends Object> T getMapper(Class<T> clazz) {
        SqlSession sqlSession = openSession();
        return sqlSession.getMapper(clazz);
    }
    //关闭连接(释放线程中的连接)
    public static void closeSession(){
        SqlSession sqlSession = tl.get();
        sqlSession.close();
        tl.remove();
    }
    //提交事务
    public static void commit(){
        SqlSession sqlSession = openSession();
        sqlSession.close();
        closeSession();
    }
    //回滚事务
    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
        closeSession();
    }
}
